<!--
  产品
 -->

<template>
  <BaseMainSlot :nowpage="nowpage">
    <template v-slot:farmtypeselectslot>
      <SelectButton
        v-if="nowpage !== 1"
        :buttonselectlist="buttonselectlist"
        @nowselectbuttonindex="topitemtype"
      />
      <el-button v-if="nowpage !== 1" class="button" size="mini" round @click="ret">返回</el-button>
    </template>
    <!-- <template v-sklot:searchbox> </template> -->
    <template v-slot:content>
      <div v-if="nowpage === 1" class="search-box">
        <div class="search">
          <div class="label-input mr-20">
            <!-- <span class="label label-80">批次名称:</span> -->
            <div class="input">
              <!-- <el-input v-model="batchName" clearable placeholder="请输入批次名称" /> -->
              <el-select
                v-model="varietyName"
                class="input-select"
                filterable
                clearable
                placeholder="请选择种养品种"
                @change="batchDataList()"
              >
                <el-option
                  v-for="(batchitem, batchindex) in varietylist"
                  :key="batchindex"
                  :label="batchitem"
                  :value="batchitem"
                />
              </el-select>
            </div>
          </div>
          <div class="label-input mr-20">
            <!-- <span class="label label-80">批次名称:</span> -->
            <div class="input">
              <!-- <el-input v-model="batchName" clearable placeholder="请输入批次名称" /> -->
              <el-select
                v-model="status"
                class="input-select"
                filterable
                clearable
                placeholder="批次情况"
                @change="batchDataList()"
              >
                <el-option :label="'已完成批次'" :value="1" />
                <el-option :label="'未完成批次'" :value="0" />
              </el-select>
            </div>
          </div>
          <div class="label-input mr-20">
            <!-- <span class="label label-80">批次名称:</span> -->
            <div class="input">
              <!-- <el-input v-model="batchName" clearable placeholder="请输入批次名称" /> -->
              <el-select
                v-model="batchName"
                class="input-select"
                filterable
                clearable
                placeholder="请选择批次名称"
                @change="search()"
              >
                <el-option
                  v-for="(batchitem, batchindex) in batchList"
                  :key="batchindex"
                  :label="batchitem.batchName"
                  :value="batchitem.batchName"
                />
              </el-select>
            </div>
          </div>
          <div class="label-input mr-20">
            <!-- <span class="label label-80">批次名称:</span> -->
            <div class="input">
              <!-- <el-input v-model="batchName" clearable placeholder="请输入批次名称" /> -->
              <StartTimeEndTimeSelectionBox
                format="yyyy-MM-dd"
                type="date"
                @startVal="startVal"
                @endVal="endVal"
              />
            </div>
          </div>
          <!-- <div class=" ml-20"> -->
          <img class="ml-20" src="~@/assets/action-bar-icon/search.png" @click="search" />
          <!-- </div> -->
        </div>
        <div class="print">
          <print :table-data="tableData" />
          <!-- <img
            class="ml-20 Screening"
            src="~@/assets/trace-source-manage/Screening.png"
            @click="screening"
          />-->
        </div>
      </div>
      <div v-if="nowpage === 1" class="content">
        <el-card v-for="item in tableData" :key="item.batchNo" class="box-card w50p">
          <!-- <el-card v-for="o in 111" :key="o" class="box-card w50p"> -->
          <!-- <div  class="text item"> -->
          <el-col :span="5" class="left">
            <el-row :gutter="18" class="left-top">
              <img
                v-if="item.varietyPicture"
                :src="'data:image/png;base64,' + item.varietyPicture"
                alt
              />
              <!-- <i v-if="!item.varietyPicture" class="el-icon-loading img"></i>-->
              <svg-icon v-if="!item.varietyPicture" class="img" :icon-class="'zanwutupian'" />
              <h6 v-if="!item.varietyPicture" style="margin: 0 auto;">暂无图片</h6>
              <!-- <img
                v-else-if="!item.varietyPicture"
                src="https://img.js.design/assets/img/615fd67a91d8f56085f05f4a.png"
                alt="默认图片"
              />-->
            </el-row>
            <el-row :gutter="6" class="left-bottom">
              <!-- <span>批次名称</span> -->
              <span>{{ item.batchName }}</span>
            </el-row>
          </el-col>
          <el-col :span="15" class="contents">
            <ul>
              <li>
                <i class="el-icon-c-scale-to-original"></i>
                <span>种养品种:</span>
                <!-- <b>红美人</b> -->
                <b>{{ item.varietyName }}</b>
              </li>
              <li>
                <i class="el-icon-time"></i>
                <span>批次日期:</span>
                <!-- <b>2020年2月12日</b> -->
                <b>{{ item.assetDate }}</b>
              </li>
              <li>
                <i class="el-icon-office-building"></i>
                <span>种养主体:</span>
                <b>农场</b>
                <b>{{ item.organizationName }}</b>
              </li>
              <li>
                <i class="el-icon-location-outline"></i>
                <span>种养地址:</span>
                <b>{{ item.plantAddress }}</b>
              </li>
            </ul>
          </el-col>
          <el-col :span="4" class="right">
            <el-row :gutter="18" class="right-top">
              <p></p>
              <vue-qr
                :text="item.downloadData.url"
                :margin="10"
                color-dark="#000"
                color-light="#fff"
                :dot-scale="1"
                :logo-scale="0.2"
                :size="200"
                :logo-src="item.downloadData.icon"
              />
            </el-row>
            <el-row :gutter="6" class="right-bottom">
              <div class="sowing-right-line-one">扫码溯源</div>
            </el-row>
          </el-col>
          <!-- </div> -->
          <div class="disnone">
            <div class="disblak">
              <i class="left"></i>
              <el-button @click="seeInformation(item)">点击查看溯源信息</el-button>
              <i class="right"></i>
            </div>
          </div>
        </el-card>
      </div>
      <!-- </div> -->
      <ProductTraceabilityTwo
        v-if="nowpage !== 1"
        ref="prouductmessage"
        :batch-from="batchFrom"
        :imgurls="imgUrl"
        :src-image="SRCImage"
      />
      <!-- <ProductTraceabilityTwo
        v-if="nowpage === 3"
        ref="prouductmessage"
        :batch-from="batchFrom"
        :imgurls="imgUrl"
      />
      <ProductTraceabilityThree
        v-if="nowpage === 4"
        ref="prouductmessage"
        :batch-from="batchFrom"
        :imgurls="imgUrl"
      />-->
      <el-dialog :title="'筛查溯源信息'" :visible.sync="dialogFormVisible">
        <!-- 111 -->
        <el-form ref="formData" label-position="left" class="w100p">
          <el-form-item label="批次列表" class="w100p checkbox">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <div class="checkboxck" style="margin: 15px 0;">
              <el-button type="text" @click="checkboxHeight">{{ checkboxName }}</el-button>
            </div>
            <div
              ref="checkboxGroup"
              class="checkbox-group"
              :style="{ height: GroupHeight }"
              style="transition: height 1s"
            >
              <el-checkbox-group v-model="batchIdList" @change="handleCheckedCitiesChange">
                <el-checkbox
                  v-for="batchitem in cities"
                  :key="batchitem.batchNo"
                  :label="batchitem.batchNo"
                >{{ batchitem.batchName }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- <el-button @click="cancel('formData')">取 消</el-button> -->
          <el-button type="primary" @click="search()">查 询</el-button>
        </div>
      </el-dialog>
    </template>
    <template v-slot:pagination>
      <Pagination
        v-if="nowpage === 1"
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import SelectButton from "@/components/selectbutton/index.vue";
import print from "../components/print/print.vue";
import vueQr from "vue-qr";
// import ProductTraceability from "../components/productionTraceability/index.vue";
import ProductTraceabilityTwo from "../components/timeline-traceability/index";
// import ProductTraceabilityThree from "../components/productionTraceabilitythree/index.vue";
// import { getToken } from "@/utils/auth";
import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";
import batchreq from "@/api/trace-source-web/common-production/index";
import BaseMainSlot from "@/components/BaseMainSlot/kong.vue";
import Pagination from "../components/Pagination/index.vue";
import { getToken, removeToken, setToken } from "@/utils/auth";

import { mymixin } from "@/utils/mixin";
import graApi from "@/api/trace-source-web/production-api/index-primary.js";

export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "timelineTraceabilitys",
  components: {
    BaseMainSlot,
    SelectButton,
    // ProductTraceability,
    ProductTraceabilityTwo,
    // ProductTraceabilityThree,
    Pagination,
    vueQr,
    print,
    StartTimeEndTimeSelectionBox
  },
  mixins: [mymixin],
  data() {
    return {
      nowpage: 1,
      topitemtypeid: 1,
      currentPage: 1,
      pageSize: 6,
      batchName: "",
      batchIdList: [],
      batchList: [],
      batchNo: "",
      batchFrom: {},
      imgUrl: "",
      dialogFormVisible: false,
      // 批次列表
      checkAll: false,
      cities: [],
      isIndeterminate: true,
      GroupHeight: "100px",
      checkboxName: "展开",
      buttonselectlist: [
        // { name: "按照类别溯源" },
        // { name: "按时间线溯源" },
        // { name: "按照日期溯源" }
      ],
      SRCImage: "",
      varietylist: [],
      varietyName: "",
      startTime: "",
      endTime: "",
      status: ""
      // 二维码数据
      // downloadData: {
      //   url: '${this.$webSerUrl}source/#/?batchNo=3&databaseName="DB_TDW1_CXXC"',
      //   icon: require('@/assets/trace-source-manage/yezi.png')
      //   // icon: 'https://img.js.design/assets/img/615fd67a91d8f56085f05f4a.png'
      // }
    };
  },
  watch: {},
  // created() {
  //   this.getTableDataList();
  // },
  created() {
    if (getToken("traceabilityNo") && getToken("traceabilityObj")) {
      this.nowpage = 2;
      this.batchNo = getToken("traceabilityNo");
      this.batchFrom = JSON.parse(getToken("traceabilityObj"));
      clearTimeout();
      setToken("traceabilityNo", this.batchFrom.batchNo);
      setToken(
        "traceabilityObj",
        JSON.stringify({
          batchNo: this.batchFrom.batchNo,
          traceSource: {
            batchType: this.batchFrom.traceSource.batchType
          }
        })
      );
      setTimeout(() => {
        removeToken("traceabilityNo");
        removeToken("traceabilityObj");
      }, 10 * 60 * 1000);
    }
  },
  mounted() {
    this.traceCode();
    this.getbatchselect();
    window.addEventListener("scroll", this.load, { passive: false });
    // console.log(window.addEventListener)
  },
  destroyed() {
    window.removeEventListener("scroll", this.load, false);
  },
  methods: {
    batchDataList() {
      this.batchName = "";
      batchreq
        .querybylist({
          farmingTypeNo: sessionStorage.farmingTypeNo,
          status: this.status,
          varietyName: this.varietyName || undefined
        })
        .then(res => {
          this.batchList = res.data;
          this.cities = res.data;
          // this.varietylist = this.batchList.map(item => item.varietyName)
        });
      this.search();
    },
    // // 无限滚动加载
    // load() {
    //   let vm = this;
    //   console.log("1")
    //   if (getScrollTop() + getWindowHeight() >= getScrollHeight()) {
    //     if (vm.currentPage < vm.totalPages) { // 先判断下一页是否有数据
    //       vm.currentPage = vm.currentPage + 1; // 查询条件的页码+1
    //       vm.getTableDataList(); // 拉取接口数据
    //     } else {
    //     // 到底了
    //       this.$message.warning("到底了")
    //     }
    //   }
    // },
    ret() {
      this.nowpage = 1;
      removeToken("traceabilityNo");
      removeToken("traceabilityObj");
    },
    // 获取点击的分页index
    topitemtype(e) {
      this.topitemtypeid = e;
      this.nowpage = e;
      // console.log(e)
      // 获取表格数据
      // this.getTableDataList();
    },
    seeInformation(val) {
      this.nowpage = 2;
      this.batchNo = val.batchNo;
      this.batchFrom = val;

      setToken("traceabilityNo", val.batchNo);
      setToken(
        "traceabilityObj",
        JSON.stringify({
          batchNo: val.batchNo,
          traceSource: {
            batchType: val.traceSource.batchType
          }
        })
      );
      clearTimeout();
      setTimeout(() => {
        removeToken("traceabilityNo");
        removeToken("traceabilityObj");
      }, 10 * 60 * 1000);
      // this.imgUrl = img;
    },
    traceCode() {
      graApi.traceCodeImage(getToken("organizationNo")).then(res => {
        // console.log(res.data)
        let data = res.data;
        if (data.length > 0) {
          this.SRCImage = "data:image/png;base64," + data[0]?.imageData;
        }
        // console.log(this.SRCImage)
        this.getTableDataList();
      });
    },
    getTableDataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          batchName: this.batchName || undefined,
          farmingTypeNo: sessionStorage.farmingTypeNo,
          organizationNo: sessionStorage.organizationNo,
          startTime: this.startTime || undefined,
          endTime: this.endTime || undefined,
          status: this.status,
          // batchIdList: this.batchIdList,
          varietyName: this.varietyName || undefined
        }
      };
      this.tableData = [];
      batchreq.getTraceabilityList(params).then(res => {
        let data = res.data;
        // console.log(data)
        this.totalSize = data.totalElements;
        this.tableData = data.content;
        this.databaseName = getToken("databaseName");
        if (this.tableData) {
          this.tableData.forEach(item => {
            // let zhurl = `${this.$webSerUrl}traceSo/#/?batchNo=${this.batchNo}&databaseName=${this.databaseName}`
            let downloadData = {
              url: `${this.$webSerUrl}mateFarmTraceSource/#/pages/production-trace/production-trace?batchNo=${item.batchNo}&databaseName=${this.databaseName}&batchType=${item.traceSource.batchType}`,
              icon: this.SRCImage
              //  || require("@/assets/trace-source-manage/yezi.png")
            };
            this.$set(item, "downloadData", downloadData);
            // if (item.plantVarietyNo) {
            //   this.feignInfoData(item.plantVarietyNo).then(url => {
            //     this.$set(item, "varietyPicture", url);
            //   });
            // }
          });
          if (this.dialogFormVisible === true) {
            this.dialogFormVisible = false;
          }
        }
        this.feignInfoImgUrl();

        // this.tableData.sort(function(a, b) {
        //   return b.assetDate < a.assetDate ? -1 : 1
        // })
        // if (this.currentPage === 1) { // 第一页就直接赋值
        //   this.totalPages = data.totalPages; // 将后台的总页数赋值
        //   this.tableData = data.content;
        // } else { // 将后面页码的数据和之前的数据拼合
        //   for (let i in data.content) {
        //     this.tableData.push(data.content[i]);
        //   }
        // }
        // console.log(this.tableData)
      });
    },
    async feignInfoImgUrl() {
      let imgNo = this.tableData.map(item => item.plantVarietyNo);
      let ImgList = [];
      let ImgNoList = [];
      if (imgNo.length > 0) {
        ImgList = [...new Set(imgNo)];
      }
      await ImgList.forEach(async (item, index) => {
        await this.feignInfoData(item).then(url => {
          ImgNoList.push({
            varietyPicture: url,
            plantVarietyNo: item
          });
          // if (index === ImgList.length - 1) {
          // this.$nextTick(() => {
          // console.log(item, index)
          this.tableData.forEach(itemx => {
            // if (itemx.plantVarietyNo) {
            ImgNoList.forEach(items => {
              if (items.plantVarietyNo === itemx.plantVarietyNo) {
                this.$set(itemx, "varietyPicture", items.varietyPicture);
              }
            });
            // }
          });
          // })
          // }
        });
      });
    },
    startVal(e) {
      this.startTime = e;
    },
    endVal(e) {
      this.endTime = e;
    },
    async feignInfoData(id) {
      // let pictureData = ''
      const { data: res } = await batchreq.feignInfo(id);
      if (res !== undefined) {
        return res.pictureData;
      } else {
        return "";
      }
    },
    // 获取批次下拉数据
    getbatchselect() {
      batchreq
        .querybylist({ farmingTypeNo: sessionStorage.farmingTypeNo })
        .then(res => {
          this.batchList = res.data;
          this.cities = res.data;
          // this.varietylist = this.batchList.map(item => item.varietyName)
        });
      batchreq
        .queryriebylist(sessionStorage.farmingTypeNo, {
          farmingTypeNo: sessionStorage.farmingTypeNo
        })
        .then(res => {
          this.varietylist = res.data;
          // this.varietylist = this.batchList.map(item => item.varietyName)
        });
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    screening() {
      this.dialogFormVisible = true;
    },
    handleCheckAllChange(val) {
      let cities = this.batchList.map(item => item.batchNo);
      this.batchIdList = val ? cities : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      // console.log(value)
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    // 点击展开
    checkboxHeight() {
      let GroupHeight = this.$refs.checkboxGroup.clientHeight;
      if (GroupHeight <= 120) {
        this.GroupHeight = "400px";
        this.checkboxName = "展开";
      } else {
        this.GroupHeight = "120px";
        this.checkboxName = "收起";
      }
      // return val
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";
@import "~@/styles/trace.scss";
::v-deep .el-form-item__label {
  color: #000 !important;
}
::v-deep .el-form-item__content {
  .el-input__inner {
    color: #000 !important;
  }
}
::v-deep .el-dialog__wrapper {
  .el-dialog {
    // width: 50% !important;

    // width: 55% !important;
    min-width: 55%;
    .el-dialog__body {
      .el-form {
        .checkbox {
          // background: #00000000;
          display: block;
          .el-form-item__content {
            width: 95%;
            margin-left: 5%;
            display: flex;
            position: relative;
            .checkboxck {
              position: absolute;
              top: -15px;
              left: 57px;
              // .el-button {
              // }
              .el-button--medium {
                padding: 0;
              }
            }
            .el-checkbox__input.is-indeterminate {
              .el-checkbox__inner {
                background-color: rgba(0, 110, 145, 1);
                border-color: rgba(0, 110, 145, 1);
              }
              .el-checkbox__label {
                color: rgba(0, 110, 145, 1);
              }
            }
            .el-checkbox.is-checked {
              .el-checkbox__inner {
                background-color: rgba(0, 110, 145, 1);
                border-color: rgba(0, 110, 145, 1);
              }
              .el-checkbox__label {
                color: rgba(0, 110, 145, 1);
              }
            }
            .checkbox-group {
              padding-left: 10px;
              min-height: 120px;
              overflow-y: auto;
              .el-checkbox {
                padding: 2px 10px;
                border: 1px solid rgba(220, 223, 230, 1);
                border-radius: 5px;
                margin-bottom: 10px;
              }
              .el-checkbox.is-checked {
                border: 1px solid rgba(0, 110, 145, 1);
                .el-checkbox__label {
                  color: rgba(0, 110, 145, 1);
                }
              }
            }
          }
        }
      }
    }
  }
}
.print {
  display: flex;
}
</style>
